package com.infodeli.user.dialog.service.impl;

import com.infodeli.common.utils.ComTool;
import com.infodeli.component.bean.Message;
import com.infodeli.user.dialog.entity.DialogRelationEntity;
import com.infodeli.user.dialog.service.DialogRelationService;
import com.infodeli.user.dialog.vo.DialogDetailVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.infodeli.common.utils.PageUtils;
import com.infodeli.common.utils.Query;

import com.infodeli.user.dialog.dao.DialogDetailDao;
import com.infodeli.user.dialog.entity.DialogDetailEntity;
import com.infodeli.user.dialog.service.DialogDetailService;


@Service("dialogDetailService")
public class DialogDetailServiceImpl extends ServiceImpl<DialogDetailDao, DialogDetailEntity> implements DialogDetailService {

    @Autowired
    DialogRelationService dialogRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DialogDetailEntity> page = this.page(
                new Query<DialogDetailEntity>().getPage(params),
                new QueryWrapper<DialogDetailEntity>()
        );

        return new PageUtils(page);
    }




    @Override // 没有进行分页查询
    public List<DialogDetailVo> getDetailByDialogId(Long dialogId, Long uid) {
        QueryWrapper<DialogDetailEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("dial_id", dialogId);

        List<DialogDetailEntity> list = this.list(wrapper); // 进行查询（没有分页）
        //IPage<DialogDetailEntity> iPage = this.page(new Query<DialogDetailEntity>().getPage(params), wrapper);// 进行查询（分页）


        // 查询对应的dialogRelation
        //DialogRelationEntity dialogRelationEntity = dialogRelationService.getById(dialogId);
        DialogRelationEntity dialogRelationEntity = resetUnreadStatus(dialogId, uid);
        // 将 unread_num 置为零，如果 unread_id 等于 uid 的话

        List<DialogDetailVo> voList = list.stream().map(entity -> {
            DialogDetailVo vo = new DialogDetailVo();
            BeanUtils.copyProperties(entity, vo);
            if (entity.getSendStatus() == 0 && dialogRelationEntity.getUserSend() == uid) {
                vo.setIsMine(1);
            } else if (entity.getSendStatus() == 1 && dialogRelationEntity.getUserRecv() == uid) {
                vo.setIsMine(1);
            } else {
                vo.setIsMine(0);
            }
            return vo;
        }).collect(Collectors.toList());

        return voList;

    }

    @Override // 进行分页查询
    public PageUtils queryPagByDialogId(Map<String, Object> params, Long dialogId, Long detailId,Long uid) {
        // todo：查询时，以detailId 或 createTime 作为where，获取前n条，而不直接采用分页【推荐：detailId】

        resetUnreadStatus(dialogId, uid);

        QueryWrapper<DialogDetailEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("dial_id", dialogId);
        if(detailId != 0){
            wrapper.lt("detail_id",detailId);
        }


        IPage<DialogDetailEntity> iPage = this.page(new Query<DialogDetailEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(iPage);
        List<?> list = pageUtils.getList();

        List<DialogDetailVo> vos = list.stream().map(entity1 -> {
            DialogDetailEntity entity = (DialogDetailEntity) entity1;
            DialogDetailVo vo = new DialogDetailVo();
            BeanUtils.copyProperties(entity, vo);
            if (entity.getUserSend() == uid) {
                vo.setIsMine(1);
            } else {
                vo.setIsMine(0);
            }
            return vo;
        }).collect(Collectors.toList());
        Collections.reverse(vos); // 反转一下
        pageUtils.setList(vos);

        return pageUtils;
    }

    // 获取消息时，视情况将unreadStatus置零
    public DialogRelationEntity resetUnreadStatus(Long dialogId, Long uid){
        DialogRelationEntity entity = dialogRelationService.getById(dialogId);
        if(entity.getUnreadId() == uid && entity.getUnreadNum() != 0){
            //entity.setUnreadNum(0);
            DialogRelationEntity updateEntity = new DialogRelationEntity();
            updateEntity.setDialId(dialogId);
            updateEntity.setUnreadNum(0);
            dialogRelationService.updateById(updateEntity);
            System.out.println("清除"+dialogId+"对话 "+uid+" 的未读");;
        }
        return entity;
    }

    @Override // 增加消息
    public void addMessage(Message message) {
        // 1、修改dialogRelation：update_time、new_content、unread_id、unread_num 以及 对方的showStatus
        DialogRelationEntity drEntity = new DialogRelationEntity();
        drEntity.setDialId(message.getDialogId());
        drEntity.setNewTime(ComTool.getDateStr());
        if(message.getContent().length()>10) {
            drEntity.setNewContent(message.getContent().substring(0, 10));
        }else{
            drEntity.setNewContent(message.getContent());
        }

        drEntity.setUnreadId(message.getRecvUid());
        DialogRelationEntity entity = dialogRelationService.getById(message.getDialogId());
        if(message.getRecvUid() == entity.getUserSend()){
            drEntity.setShowStatusSend(1);
        }else{
            drEntity.setShowStatusRecv(1);
        }
        drEntity.setUnreadNum(entity.getUnreadNum()+1);

        dialogRelationService.updateById(drEntity);

        // 2、将消息保存到dialogDetail：
        DialogDetailEntity ddEntity = new DialogDetailEntity();
        ddEntity.setDialId(message.getDialogId());
        ddEntity.setContent(message.getContent());
        ddEntity.setCreateTime(ComTool.getDateStr());
        if(message.getSendUid() == entity.getUserSend()){
            ddEntity.setSendStatus(0);
        }else{
            ddEntity.setSendStatus(1);
        }
        ddEntity.setShowStatus(1);
        ddEntity.setReadStatus(0);
        ddEntity.setUserSend(message.getSendUid());
        this.save(ddEntity);
    }

    @Override // 管理员 查看 对话详情
    public PageUtils queryPageAdmin(Map<String, Object> params, Long dialId) {
        QueryWrapper<DialogDetailEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("dial_id", dialId);
        IPage<DialogDetailEntity> page = this.page(
                new Query<DialogDetailEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


}